package com.zhfj.dao.base;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created on 2017/12/1.
 * dao层基础操作的实现
 * @author Jie
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements BaseDao<T> {

    private Class<T> clazz;


    /**
     * 通过构造方法指定DAO的具体实现类
     */
    public BaseDaoImpl(){
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }

    // TODO: 2017/12/1 这里可以使用@Autowired试一下
    @Resource
    private SessionFactory sessionFactory;


    /**
     * 获取当前工作的session
     * @return  session
     */
    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }



    @Override
    public void save(T entity) {
        this.getSession().save(entity);
    }

    @Override
    public void update(T entity) {
        this.getSession().update(entity);
    }

    @Override
    public void delete(Serializable id) {
        this.getSession().delete(this.findById(id));
    }

    @Override
    public T findById(Serializable id) {
        return (T)this.getSession().get(this.clazz,id);
    }

    @Override
    public Query findByHQLReturnQuery(String hql, Object... params) {
        Query query = this.getSession().createQuery(hql);
        for(int i = 0; params!=null && i < params.length; i++) {
            query.setParameter(i,params[i]);
        }
        return query;
    }

    @Override
    public List<T> findByHQLReturnList(String hql, Object... params) {
        return findByHQLReturnQuery(hql,params).list();
    }


}
